package org.example.rpc.framework;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * @Desc: 处理服务端逻辑
 */
public class ProcessHandler implements Runnable {
    private Socket socket;

    public ProcessHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        ObjectInputStream objectInputStream = null;
        ObjectOutputStream objectOutputStream = null;

        try {
            objectInputStream = new ObjectInputStream(socket.getInputStream());
            RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();

            Class clazz = null;
            // 判断是否存在于注册中心中
            if (Registry.containsKey(rpcRequest.getClassName())){
                clazz = Registry.get(rpcRequest.getClassName());
            }
            Method method = clazz.getMethod(rpcRequest.getMethodName(), rpcRequest.getTypes());
            Object result = method.invoke(clazz.newInstance(), rpcRequest.getParams());

            // 返回结果
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(result);
            objectOutputStream.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }finally {
            try {
                if (objectInputStream !=null){
                    objectInputStream.close();
                }
                if (objectOutputStream !=null){
                    objectOutputStream.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }

        }
    }
}

